<template>
  <a-form-item
    label="生产任务"
    :labelCol="labelCol"
    :wrapperCol="wrapperCol"
    has-feedback
  >
    <div style="margin-right: 1px; ">
      <a-button @click="add(-1,{ })" type="primary">新增</a-button>
      <a-button @click="$refs.workStepTableSel.open()">从工序中添加</a-button>
      <a-button @click="$refs.workRouteSel.open()">从模板（工艺路线）中添加</a-button>
      <a-button
        @click="$refs.addWorkRoute.add({
          workStepRouteList: tableData
        })">
        保存为模板（工艺路线）
      </a-button>
      <a-button @click="del" type="danger" :disabled="delDisable">删除</a-button>
    </div>
    <vxe-table
      :column-config="{resizable: true}"
      :row-config="{isHover: true}"
      align="center"
      ref="xTable"
      max-height="280"
      border
      show-overflow
      :key="tableKey"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'cell'}"
      @checkbox-all="checkboxAll"
      @checkbox-change="checkboxChange"
    >
      <vxe-table-column min-width="60" >
        <template v-slot>
          <!-- 鼠标悬停可拖拽-->
          <span class="drag-btn" style="cursor: pointer">
            <i class="vxe-icon--menu" style="font-size: 20px ;margin-left: 10px; vertical-align: center" ></i>
            <a-icon type="ordered-list" v-if="icon" />
            <!--            <a-icon type="column-height" v-if="!icon" />-->
          </span>
        </template>
        <template v-slot:header>
          <vxe-tooltip content="按住后可以上下拖动排序！" enterable>
            <i class="vxe-icon--question"></i>
          </vxe-tooltip>
        </template>
      </vxe-table-column>
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" min-width="60"></vxe-column>
      <vxe-column min-width="100" field="workStepId" title="工序" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ formatWorkStep(row.workStepId) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select
            v-model="row.workStepId"
            transfer
            @change="workStepChange(row, $event)">
            <vxe-option v-for="item in workStepList" :key="item.id" :value="item.id" :label="item.name"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column min-width="100" field="plaNum" title="计划数" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.plaNum" type="number" placeholder="请输入计划数"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column min-width="250" field="reportRight" title="报工权限" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ formatReportRight(row.reportRight) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select
            multiple
            v-model="row.reportRight"
            transfer>
            <vxe-option v-for="item in userList" :key="item.id" :value="item.id" :label="item.name"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <!--      <vxe-column min-width="100" field="goodNum" title="良品数" :edit-render="{}">-->
      <!--        <template #edit="{ row }">-->
      <!--          <vxe-input v-model="row.goodNum" type="number" placeholder="请输入良品数"></vxe-input>-->
      <!--        </template>-->
      <!--      </vxe-column>-->
      <vxe-column min-width="200" field="mulBadItem" title="不良品项" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ formatMulBadItem(row.mulBadItem) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select v-model="row.mulBadItem" multiple transfer>
            <vxe-option v-for="item in badItemList" :key="item.code" :value="item.code" :label="item.name"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column min-width="200" field="plaStartTime" title="计划开始时间" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.plaStartTime" type="datetime" placeholder="请选择计划开始时间" transfer></vxe-input>
        </template>
      </vxe-column>
      <vxe-column min-width="200" field="plaEndTime" title="计划结束时间" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.plaEndTime" type="datetime" placeholder="请选择计划结束时间" transfer></vxe-input>
        </template>
      </vxe-column>
    </vxe-table>
    <work-step-table-sel
      ref="workStepTableSel"
      @confirm="handleWorkStepTableConfirm"
      @ok="getWorkStepList()"/>
    <work-route-sel ref="workRouteSel" @confirm="handleWorkRouteConfirm"/>
    <add-work-route
      ref="addWorkRoute"
      @ok="()=>{
        $refs.workRouteSel.getWorkRouteList()
      }"
    />
  </a-form-item>

</template>

<script>
import VXETable from 'vxe-table'
import Sortable from 'sortablejs'
import { mapGetters } from 'vuex'
import workStepTableSel from '@/views/main/workorder/workStepTableSel'
import workRouteSel from '@/views/main/workorder/workRouteSel'
import UserSelect from '@/components/MyComp/UserSelect'
import { getUserPage } from '@/api/modular/system/userManage'
import { workStepList } from '@/api/modular/main/workstep/workStepManage'
import addWorkRoute from '@/views/main/workroute/addForm'

export default {
  name: 'TableFormItem',
  components: {
    workStepTableSel,
    workRouteSel,
    UserSelect,
    addWorkRoute
  },
  props: {
    oldTableData: {
      type: Array,
      require: false,
      default() {
        return []
      }
    },
    badItemList: {
      type: Array,
      require: false,
      default() {
        return []
      }
    },
    plaNum: {
      type: Number,
      require: false,
      default: null
    },
    plaStartTime: {
      type: String,
      require: false,
      default: null
    },
    plaEndTime: {
      type: String,
      require: false,
      default: null
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  data () {
    return {
      tableData: [],
      workStepList: [],
      userList: [],
      delDisable: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      // 组件key发生变化，则会强制对该组件进行刷新
      tableKey: 0,
      icon: true
    }
  },
  created() {
    this.tableData = this.oldTableData
  },
  mounted() {
    this.drag()
    this.getWorkStepList()
    getUserPage({
      pageNo: 1,
      pageSize: -1
    }).then((res) => {
      this.userList = res.data.rows
    })
  },
  methods: {
    drag() {
      this.$nextTick(() => {
        Sortable.create(this.$refs.xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'),
          {
            handle: '.drag-btn',
            animation: 150,
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0]
              this.tableData.splice(newIndex, 0, currRow)
              this.tableKey++
            }
          }
        )
      })
    },
    getWorkStepList() {
      workStepList().then(res => {
        this.workStepList = res.data
      })
    },
    // 选中工序表确认方法
    handleWorkStepTableConfirm(data) {
      data.forEach(item => {
        this.add(-1, {
          workStepId: item.id,
          mulBadItem: item.mulBadItem ? item.mulBadItem.split(';') : null,
          reportRight: item.reportRight ? item.reportRight.split(';') : null
        })
      })
    },
    // 选中工序确认方法
    handleWorkRouteConfirm(data) {
      if (data && data.workStepRouteList && data.workStepRouteList.length > 0) {
        // 注意要先进行排序
        this.$utils.orderBy(data.workStepRouteList, [['sortNum', 'asc']]).forEach(item => {
          this.add(-1, {
            workStepId: item.workStepId,
            mulBadItem: item.mulBadItem ? item.mulBadItem.split(';') : null,
            reportRight: item.reportRight ? item.reportRight.split(';') : null
          })
        })
      }
    },
    formatReportRight(values) {
      if (!this.$utils.isEmpty(values) && this.$utils.isArray(values)) {
        return values.map(val => this.$utils.find(this.userList, item => item.id === val)?.name).join(';')
      }
      return values
    },
    formatMulBadItem (values) {
      if (!this.$utils.isEmpty(values) && this.$utils.isArray(values)) {
        return values.map(val => this.$utils.find(this.badItemList, item => item.code === val)?.name).join(';')
      }
      return values
    },
    formatWorkStep (value) {
      return this.$utils.find(this.workStepList, item => item.id === value)?.name
    },
    // 新增方法
    async add(row, record) {
      // 良品数量
      record.goodNum = 0

      // 计划数
      const plaNum = this.plaNum
      if (plaNum) {
        record.plaNum = plaNum
      }
      // 开始时间
      const plaStartTime = this.plaStartTime
      if (plaStartTime) {
        record.plaStartTime = plaStartTime
      }
      // 结束时间
      const plaEndTime = this.plaEndTime
      if (plaEndTime) {
        record.plaEndTime = plaEndTime
      }
      // 表格数据进行新增
      await this.$refs.xTable.insertAt(record, row)
      Object.assign(this.tableData, this.$refs.xTable.getTableData().tableData)
    },
    // 删除方法
    async del () {
      // 弹出框
      const type = await VXETable.modal.confirm('您确定要删除该数据?')
      if (type === 'confirm') {
        await this.$refs.xTable.removeCheckboxRow()
      }
      this.tableData = this.$refs.xTable.getTableData().tableData
      this.isDisableDel()
    },
    // 删除按钮是否禁用
    isDisableDel() {
      // 如果选择的记录为零则进行
      this.delDisable = this.$refs.xTable.getCheckboxRecords().length <= 0
    },
    // 全部选中
    checkboxAll({ checked, $event }) {
      this.isDisableDel()
    },
    // 选中变化
    checkboxChange({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
      this.isDisableDel()
    },
    // 改变工序值改变相应报工权限,不良品项的值
    workStepChange(row, val) {
      const workStep = this.$utils.find(this.workStepList, item => item.id === val.value)
      if (workStep.mulBadItem) {
        row.mulBadItem = workStep.mulBadItem.split(';')
      }
      if (workStep.reportRight) {
        row.reportRight = workStep.reportRight.split(';')
      }
    }
  },
  watch: {
    //  监听tableData变化
    tableData: {
      handler() {
        this.$emit('tableDataChange', this.tableData)
      },
      deep: true
    },
    tableKey: {
      handler() {
        //  表格数据刷新后重新调用拖拽方法
        this.drag()
      },
      deep: true
    }
  }
}
</script>
